<?php
  define('BASE_URL', '/report/index?');

  function renderMonth($month, $caption)
  {
    $day_names = array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
    $url = BASE_URL.'day=';
    $calendar = '<table class="calendar" width="220"><caption class="calendar-month">'.$caption.'</caption><tr>';
    foreach($day_names as $name) {
      $calendar .= '<th>'.$name.'</th>';
    }
    $calendar .= '</tr>';
    $len = count($day_names);
    foreach ($month as $week) {
      $calendar .= '<tr>';
      foreach ($week as $i => $day) {
        if ($i == 0 || $i == 6) {
          $calendar .= '<td>'.$day.'</td>';
        } else {
          $calendar .= '<td><a href="'.$url.$caption.'-'.$day.'">'.$day.'</a></td>';
        }
      }
      $calendar .= '</tr>';
    }
    return $calendar;
  }
  
  function renderNav($last, $next)
  {
    $nav = '<table class="calendar-nav" width="220"><tr>';
    if ($last < 1) {
      $prev = '<td> </td>';
    } else {
      $url = url_for(BASE_URL.'month='.$last);
      $prev = '<td><a href="'.$url.'">prev</a></td>';
    }
    if ($next > 10) {
      $next = '<td> </td>';
    } else {
      $url = url_for(BASE_URL.'month='.$next);
      $next = '<td><a href="'.$url.'">next</a></td>';
    }
    $nav .= $prev.'<td colspan="5" width="100"></td>'.$next;
    return $nav;
  }
  
  function renderTotal($months, $selday, $month = null)
  {
    $start = isset($month) ? $month : date('m', strtotime($selday));
    if ($start > 1) $start--;
    if ($start < 1) $start = 1;
    if ($start > 10) $start = 10;
    $year = date('Y', strtotime($selday));
    
    $calendar = '';
    $end = $start + 3;
   
    $nav = renderNav($start - 1, $end);
    for (; $start < $end; $start++) {
      $mon = $months[$start];
      $caption = "${year}-${start}";
      $calendar .= renderMonth($mon, $caption);
    }
    $calendar .= $nav;
    return $calendar;
  }
  
  echo renderTotal($months, $today, $month);
  
?>